package Socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
聊天室的服务器端

为了实现聊天资源的共享
 */
public class Server5 {

    private ServerSocket serverSocket;//声明一个 电话总机  serverSocket

    ArrayList<PrintWriter> allOut =new ArrayList<>();//该集合用于保存客户端的输出流，用于广播信息

    public Server5() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  //无参构造，在创建服务器对象时候创建端口并赋值端口号

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println( "客户端"+socket.getInetAddress()+"已经连接");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
            //循环接电话，并创建新的线程-->调用  电话处理  方法

            /*服务器接收消息*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server5 server = new Server5();
        server.start();
    }//main方法中创建服务器对象，并开启服务器start方法

    /*
     * 定义内部类与客户端交互
     * */
    private class ClientHandler implements Runnable {
        private Socket socket;  //在服务器 声明一个socket
        private String host;  //记录客户端IP地址

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }//用构造方法把“外接来的电话 转到的 服务器的socket”接收

        @Override
        public void run() {
            //关于客户端的地址
            InetAddress inetAddress = socket.getInetAddress();
            String host=String.valueOf(inetAddress);
            String subAd=host.substring(host.lastIndexOf('.'));

            PrintWriter pw=null;
            try {
                //服务器接收信息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);


                //服务器发送消息
                OutputStream out=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw=new BufferedWriter(osw);
                pw=new PrintWriter(bw,true);

                //锁住集合的添加动作，防止在添加过程中切换到其他线程执行该操作。
                synchronized (allOut) {
                    allOut.add(pw);
                }


                //广播消息，上线的提示
                broadCast(subAd+"上线了，当前在线人数："+allOut.size());



                String message;
                try {
                    while ((message = br.readLine()) != null) {
                        broadCast(subAd+" 说："+message);
                    }
                } catch (IOException e) {

                }
            } catch (IOException e) {
                System.out.println("大概率是客户端"+host+"异常退出...");
            }finally {
                //处理客户端断开后（br.readLine()) == null）的操作
                //从集合中删除流
                synchronized (allOut) {
                    allOut.remove(pw);
                }
                //广播该客户端下线
                broadCast(subAd+"下线了  ，当前在线人数："+allOut.size());

                try {
                    socket.close();
                } catch (IOException e) {

                }

            }

        }

        //广播
        private void broadCast(String cast){
            System.out.println(cast);
            //要求遍历的时候不能增删元素
            synchronized (allOut) {
                for(PrintWriter o:allOut){
                    o.println(cast);
                }
            }
        }

    }


}
